<?php

namespace app\api\controller\app;

use addons\epay\library\Service;
use app\admin\model\Article;
use app\admin\model\Articletype;
use app\admin\model\City;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopdou;
use app\admin\model\Shopjoin;
use app\admin\model\Shopks;
use app\admin\model\Shopmeituan;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoptuan;
use app\admin\model\Tuanorder;
use app\admin\model\Userbalance;
use app\admin\model\Userdoucode;
use app\admin\model\Userkscode;
use app\admin\model\Usermeituancode;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\api\service\KsService;
use app\api\service\MtService;
use app\api\service\MtUtil;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;

/**
 */
class Douks extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $appKey = "";
    protected $secret = "";

    public function _initialize()
    {
        parent::_initialize();
        $this->appKey = "awoh1q4tfg29z1yv";
        $this->secret = "b8976219b329b01d543e76a83c923720";
    }

    public function checkCode()
    {

        $shop_id = $this->request->param('shopId');
        if(!$shop_id){
            $shop_id = $this->request->param('shop_id');
        }
        $user = $this->auth->getUser();
        $code = $this->request->param('code');
        $back = array();
        if(strlen($code) == 15 || substr($code, 0, 16) == "https://ksurl.cn"){
            //快手
            $back['type'] = "ks";

            $ksService  = new KsService();
            $req = array();
            $req['shop_id'] = $shop_id;
            $req['code'] = $code;
            $result = $ksService->prepare($this->longRedis,$req);
            if($result['code'] == 0){
                $this->error($result['msg']);
            }
            $shopKsModel = new Shopks();
            $shopDou = $shopKsModel->where('sku_id',$result['sku_id'])->where('shop_id',$shop_id)->find();
            if(!$shopDou) $this->error("店铺未同步该券产品，请联系商家");
            $userKsCodeModel = new Userkscode();
            $userCode = $userKsCodeModel->where('ks_code',$code)->find();
            if(!$userCode){
                $id = $userKsCodeModel->insertGetId(['user_id'=>$user['id'],'ks_code'=>$code,'create_time'=>time(),'sku_id'=>$result['sku_id'],'shop_id'=>$shop_id]);
            }else{
                $userKsCodeModel->where('id',$userCode['id'])->update(['user_id'=>$user['id'],'ks_code'=>$code,'create_time'=>time(),'sku_id'=>$result['sku_id'],'shop_id'=>$shop_id]);
                $id = $userCode['id'];
            }
            $back['id'] = $id;

        }else{
            $back['type'] = "dou";
            //抖音
            $tokenUrl = "https://open.douyin.com/oauth/client_token/";
            $tokenReq = array();
            $tokenReq["client_key"] = $this->appKey;
            $tokenReq["client_secret"] = $this->secret;
            $tokenReq["grant_type"] = "client_credential";

            $result = $this->curl_post($tokenUrl, $tokenReq);
            $token = $result['data']['access_token'];

            if (substr($code, 0, 5) == "https") {

                $headers = get_headers($code, TRUE);
                $reqUrl = $headers['Location'];
                $data = parse_url($reqUrl);
                parse_str($data['query'], $results);
                $objData = $results['object_id'];
                $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
            } else {
                $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" .$code;
            }


            $result = $this->http_curl_get($url, $token);

            if($result['data']['error_code'] != 0){
                $this->error($result['data']['description']);
            }
            $certificates = $result['data']['certificates'];
            if(count($certificates) == 0){
                $this->error("此券码错误");
            }

            $skuId = $certificates[0]['sku']['sku_id'];

            $shopDouModel = new Shopdou();
            $shopDou = $shopDouModel->where('sku_id',$skuId)->find();
            if(!$shopDou) $this->error("店铺未同步该券产品，请联系商家");

            if($shop_id == ""){
                $shop_id= $shopDou['shop_id'];
            }

            $douUserCodeModel = new Userdoucode();
            $userCode = $douUserCodeModel->where('dou_code',$code)->find();
            if(!$userCode){
                $id = $douUserCodeModel->insertGetId(['user_id'=>$user['id'],'dou_code'=>$code,'create_time'=>time(),'sku_id'=>$skuId,'shop_id'=>$shop_id]);
            }else{
                $douUserCodeModel->where('id',$userCode['id'])->update(['user_id'=>$user['id'],'dou_code'=>$code,'create_time'=>time(),'sku_id'=>$skuId,'shop_id'=>$shop_id]);
                $id = $userCode['id'];
            }
            $back['id'] = $id;

        }
        $this->success("成功",$back);
    }

    public function userCodeDetail(){

        $id = $this->request->param('id');
        $type = $this->request->param();
        $ret = array();

        if($type == 'dou'){
            $douUserCodeModel = new Userdoucode();
            $dou = $douUserCodeModel->where('id',$id)->find();

            $shopModel = new Shop();
            $shop = $shopModel->where('id',$dou['shop_id'])->find();

            $shopRoomModel = new Shoproom();
            $douShopModel =new Shopdou();
            $shopDou = $douShopModel->where('shop_id',$shop['id'])->where('sku_id',$dou['sku_id'])->find();
            if(!$shopDou) $this->error("暂未关联到该券");
            error_log("====shopDou===".json_encode($shopDou));
            $rooms = json_decode($shopDou['room_id'],true);
            $roomList = array();

            $shopTableModel =  new \app\admin\model\Shoptable();
            error_log("===room===".json_encode($rooms));
            foreach ($rooms as $key=>$val){
                if($shopDou['type'] == 'qp'){
                    $roomList[] =   $shopRoomModel->where('id',$val)->find();

                }else{
                    $roomList[] = $shopTableModel->where('id',$val)->find();
                }
            }
            $week = json_decode($shopDou['week'],true);
            $weekStr = "";
            foreach ($week as $key=>$val){
                if($val == '7'){
                    $val  = "日";
                }
                $weekStr .="周".$val;
                if($key != count($week)-1){
                    $weekStr .= ",";
                }
            }
            $ret['shop_name'] = $shop['name'];
            $ret['roomList'] = $roomList;
            $ret['hour'] = $shopDou['hour'];
            $ret['time'] = $shopDou['use_time'];
            $ret['weekStr'] =$weekStr;
            $ret['sku_name'] =$shopDou['sku_name'];
            $ret['dou_code'] =$dou['dou_code'];
            $ret['shop_id'] =$shopDou['shop_id'];
            $ret['type'] =$shopDou['type'];

        }else{
            $ksUserCodeModel = new Userkscode();
            $ks = $ksUserCodeModel->where('id',$id)->find();

            $shopModel = new Shop();
            $shop = $shopModel->where('id',$ks['shop_id'])->find();

            $shopRoomModel = new Shoproom();
            $shopKsModel =new Shopks();
            $shopKs = $shopKsModel->where('shop_id',$shop['id'])->where('sku_id',$ks['sku_id'])->find();
            if(!$shopKs) $this->error("暂未关联到该券");
            $rooms = json_decode($shopKs['room_id'],true);
            $roomList = array();

            $shopTableModel =  new \app\admin\model\Shoptable();
            foreach ($rooms as $key=>$val){
                if($shopKs['type'] == 'qp'){
                    $roomList[] =   $shopRoomModel->where('id',$val)->find();

                }else{
                    $roomList[] = $shopTableModel->where('id',$val)->find();
                }
            }
            $week = json_decode($shopKs['week'],true);
            $weekStr = "";
            foreach ($week as $key=>$val){
                if($val == '7'){
                    $val  = "日";
                }
                $weekStr .="周".$val;
                if($key != count($week)-1){
                    $weekStr .= ",";
                }
            }
            $ret['shop_name'] = $shop['name'];
            $ret['roomList'] = $roomList;
            $ret['hour'] = $shopKs['hour'];
            $ret['time'] = $shopKs['use_time'];
            $ret['weekStr'] =$weekStr;
            $ret['sku_name'] =$shopKs['sku_name'];
            $ret['dou_code'] =$ks['ks_code'];
            $ret['shop_id'] =$shopKs['shop_id'];
            $ret['type'] =$shopKs['type'];
        }

        $this->success('',$ret);

    }




    public function syncGood()
    {

        $tokenUrl = "https://open.douyin.com/oauth/client_token/";
        $tokenReq = array();
        $tokenReq["client_key"] = $this->appKey;
        $tokenReq["client_secret"] = $this->secret;
        $tokenReq["grant_type"] = "client_credential";

        $result = $this->curl_post($tokenUrl, $tokenReq);
        $token = $result['data']['access_token'];


        $shop_id = 1;
        $account_id = "7208067456537987084";
        $url = "https://open.douyin.com/goodlife/v1/goods/product/online/query/?status=1&goods_creator_type=1&count=50&account_id=" . $account_id;

        $result = $this->http_curl_get($url, $token);

        $product = $result['data']['products'];

        $shopDouModel = new Shopdou();

        foreach ($product as $key => $val) {

            $db = array();
            $sku = $val['sku'];
            $skuId = $sku['sku_id'];
            $skuName = $sku['sku_name'];
            $db['sku_id'] = $skuId;
            $db['sku_name'] = $skuName;
            $db['shop_id'] = $shop_id;
            $skuDb = $shopDouModel->where('sku_id', $skuId)->find();
            if (!$skuDb) $shopDouModel->insert($db);
        }
        $this->success('成功');
    }


    //post请求
    public function curl_post($url, $postdata)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Expect:'
        )); // 解决数据包大不能提交
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


    //post请求
    public function curl_post2($url, $postdata, $token)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测

        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "access-token: " . $token));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


    public function http_curl_get($url, $token)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, 5000);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "access-token: " . $token));

        $tmpInfo = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


}
